let con = document.querySelector('.con');
let btn = document.querySelector('button');
let score = document.querySelector('.score');
let h1 = document.querySelector('h1');
let num = 0;
let speed = 10;
let flag = false;
let play = null;

//创建div, Name是类名
function createDiv(className) {
  let div = document.createElement('div');
  div.className = className;
  return div;
}

//彩色块
function isColor() {
  while (true) {
    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    if (r != 255 && g != 255 && b != 255) {
      break;
    }
  }
  return `rgba(${r},${g},${b})`;
}

//创建四个白块，将类名弄成数组
function createCell() {
  let cellArr = ['cell', 'cell', 'cell', 'cell'];
  let i = Math.round(Math.random() * 3);
  cellArr[i] = 'cell color';
  return cellArr;
}

// 创建一行，有四个块
function createRow() {
  let row = createDiv('row');
  let arr = createCell();

  con.appendChild(row);

  for (let i = 0; i < arr.length; i++) {
    row.appendChild(createDiv(arr[i]));
  }

  if (con.firstChild == null) {
    con.appendChild(row);
  } else {
    con.insertBefore(row, con.firstChild);
  }
}

//下落移动
function move() {
  let top = parseInt(window.getComputedStyle(con, null).top);

  // 更改 top值
  speed + top > 0 ? (top = 0) : (top += speed);
  con.style.top = top + 'px';

  // 当 top=0，创建新的一行并且移上去
  if (top == 0) {
    createRow();
    let color = document.querySelector('.color');
    color.style.backgroundColor = `${isColor()}`;
    con.style.top = '-100px';
  } else {
    top += speed;
  }

  fail();

  // 当row为6的时候，删除最后一个row
  if (con.childElementCount == 6) {
    con.removeChild(con.lastChild);
  }
}

//判断黑块有没有触底，触底则失败
function fail() {
  let rows = con.childNodes;
  if (rows.length == 5 && rows[rows.length - 1].pass !== 1) {
    // console.log(rows[rows.length - 1].pass !== 1);
    over();
  }
}

//点击黑块更改类名
function removeBlack(event) {
  if (flag) {
    if (event.target.className.indexOf('color') == -1) {
      over();
    } else {
      event.target.removeAttribute('style');
      event.target.parentNode.pass = 1;
      num++;
      score.innerHTML = `${num}`;

      speed <= 15 && num > 6 ? (speed += 2) : null;
    }
  }
}

//游戏结束
function over() {
  clearInterval(play);
  btn.innerHTML = `重新开始`;
  h1.innerHTML = `游戏失败，得分：${num}分`;
  flag = false;
}

btn.addEventListener('click', () => {
  if (!flag) {
    flag = true;
    score.innerHTML = 0;
    con.innerHTML = ``;
    h1.innerHTML = ``;
    btn.innerHTML = `游戏中`;
    num = 0;
    play = setInterval(move, 50);
    con = document.querySelector('.con');

    con.onclick = function (event) {
      removeBlack(event);
    };
  }
});
